package com.jy.appmarket.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jy.app.market.apk.type.UidType;
import com.jy.app.market.idata.data.Login;
import com.jy.app.market.idata.data.OtherLogin;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.dialog.WaitDialog;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.LoginNetEngine;
import com.jy.appmarket.network.engine.OtherLoginNetEngine;
import com.jy.appmarket.network.resultdata.LoginResult;
import com.jy.appmarket.network.resultdata.OtherLoginResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.utils.CryptoUtil;
import com.jy.appmarket.utils.LoginUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

import java.util.Map;

/**
 * @author :    jiangwei
 * @time :      2018/05/22
 * @desc :      登录新页面
 * @virsion :   1.0.
 */
public class UserLoginActivity extends FragmentActivity implements View.OnClickListener,NetTask.NetTaskListener {
    private ImageView ivBack;
    private TextView tvRegister;
    private EditText etPhone;
    private TextView tvForgetPassword;
    private EditText etPassword;
    private TextView tvSign;
    private TextView tvSwitch;
    private LinearLayout llLogin0r;
    private LinearLayout llLoginOther;
    private TextView tvWechat;
    private TextView tvSina;
    private TextView tvQq;

    private UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
    private WaitDialog mWaitDialog;
    private String mPhoneNum;
    private String mPasswd;

    private NetTask mNetTask;
    private NetTask mNetTask2;

    private UMQQSsoHandler mQQSsoHandler;
    private UMWXHandler mWXHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);
        initView();

        addLoginPlatform();
        // 设置新浪SSO
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
    }

    private void initView() {
        ivBack = findViewById(R.id.iv_user_login_back);
        ivBack.setOnClickListener(this);
        tvRegister = findViewById(R.id.tv_user_login_register);
        tvRegister.setOnClickListener(this);
        etPhone = findViewById(R.id.et_user_login_phone);
        tvForgetPassword = findViewById(R.id.tv_user_login_forget_password);
        tvForgetPassword.setOnClickListener(this);
        etPassword = findViewById(R.id.et_user_login_password);
        tvSign = findViewById(R.id.tv_user_login_sign);
        tvSign.setOnClickListener(this);
        tvSwitch = findViewById(R.id.tv_user_login_switch);
        tvSwitch.setOnClickListener(this);
        llLogin0r = findViewById(R.id.ll_user_login_or);
        llLoginOther = findViewById(R.id.ll_user_login_other);
        tvWechat = findViewById(R.id.tv_user_login_other_wechat);
        tvWechat.setOnClickListener(this);
        tvSina = findViewById(R.id.tv_user_login_other_sina);
        tvSina.setOnClickListener(this);
        tvQq = findViewById(R.id.tv_user_login_other_qq);
        tvQq.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.iv_user_login_back:
                finish();
                break;
            //注册
            case R.id.tv_user_login_register:
                startActivity(new Intent(UserLoginActivity.this,RegisterActivity.class));
                break;
            //忘记密码
            case R.id.tv_user_login_forget_password:
                startActivity(new Intent(UserLoginActivity.this, RetrievePasswordActivity.class));
                break;
            //登录
            case R.id.tv_user_login_sign:
                login();
                break;
            //切换其他登录方式
            case R.id.tv_user_login_switch:
                tvSwitch.setVisibility(View.GONE);
                llLogin0r.setVisibility(View.VISIBLE);
                llLoginOther.setVisibility(View.VISIBLE);
                break;
            //微信登录
            case R.id.tv_user_login_other_wechat:
                try {
                    // 这里会抛出TransactionTooLargeException
                    if (mWXHandler.isClientInstalled()) {
                        otherLogin(SHARE_MEDIA.WEIXIN);
                    } else {
                        Toast.makeText(UserLoginActivity.this, "没有安装微信", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                }
                break;
            //微博登录
            case R.id.tv_user_login_other_sina:
                otherLogin(SHARE_MEDIA.SINA);
                break;
            //qq登录
            case R.id.tv_user_login_other_qq:
                try {
                    // 这里会抛出TransactionTooLargeException
                    if (mQQSsoHandler.isClientInstalled()) {
                        otherLogin(SHARE_MEDIA.QQ);
                    } else {
                        Toast.makeText(UserLoginActivity.this, "没有安装QQ", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                }
                break;
            default:
                break;
        }
    }

    private void login() {
        mPhoneNum = etPhone.getText().toString().trim();
        mPasswd = etPassword.getText().toString();

        if (TextUtils.isEmpty(mPhoneNum)) {
            Toast.makeText(UserLoginActivity.this, R.string.please_input_username, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mPasswd)) {
            Toast.makeText(UserLoginActivity.this, R.string.please_input_password, Toast.LENGTH_SHORT).show();
            return;
        }
        if (mPhoneNum.length() != 11) {
            Toast.makeText(UserLoginActivity.this, R.string.username_format_error, Toast.LENGTH_SHORT).show();
            return;
        }

        showWaitDialog();
        LoginNetEngine engine = new LoginNetEngine(mPhoneNum, CryptoUtil.md5(mPasswd));
        mNetTask = new NetTask(UserLoginActivity.this, engine, 0);
        mNetTask.setListener(this);
        new Thread(mNetTask).start();
    }

    private void addLoginPlatform() {
        // 添加QQ平台
        mQQSsoHandler = new UMQQSsoHandler(this, "1104848831", "i4vpuXnIbjmNUEcL");
        mQQSsoHandler.addToSocialSDK();

        // 添加微信平台
        mWXHandler = new UMWXHandler(this, "wx365c6227b8b569b0", "d4624c36b6795d1d99dcf0547af5443d");
        mWXHandler.addToSocialSDK();

    }

    private OtherLogin toOtherLogin(Map<String, Object> info, String platformTyep, String uid) {
        OtherLogin otherLogin = new OtherLogin();
        if (SHARE_MEDIA.QQ.name().equals(platformTyep)) {
            otherLogin.setIconUrl(info.get("profile_image_url").toString());
            otherLogin.setNickName(info.get("screen_name").toString());
            String sex = info.get("gender").toString();
            if ("男".equals(sex)) {
                otherLogin.setSex("1");
            } else if ("女".equals(sex)) {
                otherLogin.setSex("2");
            }
            otherLogin.setType(UidType.QQ.toString());
        } else if (SHARE_MEDIA.WEIXIN.name().equals(platformTyep)) {
            otherLogin.setIconUrl(info.get("headimgurl").toString());
            otherLogin.setNickName(info.get("nickname").toString());
            otherLogin.setSex(info.get("sex").toString());
            otherLogin.setType(UidType.WEI_XIN.toString());
        } else if (SHARE_MEDIA.SINA.name().equals(platformTyep)) {
            otherLogin.setIconUrl(info.get("profile_image_url").toString());
            otherLogin.setNickName(info.get("screen_name").toString());
            otherLogin.setSex(info.get("gender").toString());
            otherLogin.setType(UidType.SINA_WB.toString());
        }
        otherLogin.setUid(uid);
        return otherLogin;
    }

    private Login toLogin(OtherLogin info) {
        Login login = new Login();
        login.setUserId(info.getUserId());
        login.setPhoneNum(info.getPhoneNum());
        login.setNickName(info.getNickName());
        login.setIconUrl(info.getIconUrl());
        login.setSex(info.getSex());
        login.setBirthday(info.getBirthday());
        return login;
    }

    private void showWaitDialog() {
        if (mWaitDialog == null) {
            mWaitDialog = new WaitDialog(this);
            mWaitDialog.setCanceledOnTouchOutside(false);
            mWaitDialog.setCancelable(false);
        }
        if (mWaitDialog.isShowing()) {
            return;
        }
        mWaitDialog.showTitle("请稍候...").show();
    }

    private void dismissWaitDialog() {
        if (mWaitDialog != null) {
            mWaitDialog.dismiss();
        }
    }

    private void otherLogin(final SHARE_MEDIA platform) {
        mController.doOauthVerify(this, platform, new SocializeListeners.UMAuthListener() {

            @Override
            public void onStart(SHARE_MEDIA platform) {
                Toast.makeText(UserLoginActivity.this, "授权开始", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
                Toast.makeText(UserLoginActivity.this, "授权错误", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                if (value == null || TextUtils.isEmpty(value.getString("uid"))) {
                    Toast.makeText(UserLoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                } else {
                    showWaitDialog();
                    Toast.makeText(UserLoginActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                    getUserInfo(platform, value.getString("uid"));
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
                Toast.makeText(UserLoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取授权平台的用户信息</br>
     */
    private void getUserInfo(final SHARE_MEDIA platform, final String uid) {
        mController.getPlatformInfo(UserLoginActivity.this, platform, new SocializeListeners.UMDataListener() {

            @Override
            public void onStart() {
                // Toast.makeText(getActivity(), "获取用户信息...",
                // Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(int status, Map<String, Object> info) {
                if (status == 200 && info != null) {
                    OtherLogin otherLogin = toOtherLogin(info, platform.name(), uid);
                    OtherLoginNetEngine engine = new OtherLoginNetEngine(otherLogin);
                    mNetTask2 = new NetTask(UserLoginActivity.this, engine, 1);
                    mNetTask2.setListener(UserLoginActivity.this);
                    new Thread(mNetTask2).start();
                } else {
                    dismissWaitDialog();
                    Toast.makeText(UserLoginActivity.this, "获取用户信息失败" + status, Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.bottom_out);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
        dismissWaitDialog();
        if (tag == 0) {
            LoginResult resultData = (LoginResult) engine.getResultData();
            if (!resultData.isOK()) {
                String message = resultData.getMessage();
                if (!TextUtils.isEmpty(message)) {
                    Toast.makeText(UserLoginActivity.this, message, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(UserLoginActivity.this, R.string.login_error, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(UserLoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                Login login = resultData.getLogin();
                AppMarketApplication.setLogin(login);
                LoginUtil.saveLogin(UserLoginActivity.this, login);
                setResult(Activity.RESULT_OK);
                finish();
            }
        } else if (tag == 1) {
            OtherLoginResult resultData = (OtherLoginResult) engine.getResultData();
            if (!resultData.isOK()) {
                String message = resultData.getMessage();
                if (!TextUtils.isEmpty(message)) {
                    Toast.makeText(UserLoginActivity.this, message, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(UserLoginActivity.this, R.string.login_error, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(UserLoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                Login login = toLogin(resultData.getOtherLogin());
                AppMarketApplication.setLogin(login);
                LoginUtil.saveLogin(UserLoginActivity.this, login);
                setResult(Activity.RESULT_OK);
                finish();
            }
        }

    }

    @Override
    public void onTaskRunError(int tag) {
        dismissWaitDialog();
        Toast.makeText(UserLoginActivity.this, R.string.network_error, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTaskRunCanceled(int tag) {
        dismissWaitDialog();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}
